import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { BillItemsEntity, ColumnItem, LabelValueEntity, stateResEntity, longDataEntity, ShortDataEntity } from './recipy-details.entity';
import { RecipyDetailsService } from './recipy-details.service';
import Singleton from '../../services/singleton';

@Component({
  selector: 'app-recipy-details',
  templateUrl: './recipy-details.component.html',
  styleUrls: ['./recipy-details.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RecipyDetailsComponent implements OnInit {
  singleton_username: Singleton;
  username: string;
  useraddress: string;

  toSplit: string;

  isVisible: boolean = false;
  modalindex: number;
  operator_count: number;
  recipy_index: number;
  recipy_ori_name: string;
  debtBillItems: BillItemsEntity[] = [];
  debtHoldingBillItems: BillItemsEntity[] = [];
  listOfOption: LabelValueEntity[] = [];
  selectedObject: string;
  debtBillContainerTab: string[] = ['20%', '20%', '20%', '40%'];
  listOfColumns: ColumnItem[] = [
    {
      name: '对方名称',
      sortOrder: null,
      sortFn: (a: BillItemsEntity, b: BillItemsEntity) => a.name.localeCompare(b.name),
    },
    {
      name: '金额',
      sortOrder: null,
      sortFn: (a: BillItemsEntity, b: BillItemsEntity) => a.moneyCount - b.moneyCount,
    },
    {
      name: '时限',
      sortOrder: null,
      sortFn: (a: BillItemsEntity, b: BillItemsEntity) => a.time.localeCompare(b.time),
    }
  ];
  constructor(
    private readonly recipyDetailsService: RecipyDetailsService,
    private def:ChangeDetectorRef
  ) { }

  

  num2str(num: number): string {
    return String(num);
  }

  showModal(num: number, index: number) {
    this.modalindex = num;
    this.isVisible = true;
    if (num == 0 || num == 1 || num == 2) {
      this.recipy_index = index;
      this.recipy_ori_name = this.debtBillItems[index].name;
    } else if (num == 3) {
      this.recipy_index = index;
      this.recipy_ori_name = this.debtHoldingBillItems[index].name;
    }
    console.log('recipy_ori_name', this.recipy_ori_name);
  }

  handleSettingCancel(): void {
    this.isVisible = false;
  }

  handleSettingOk(): void {
    this.singleton_username = Singleton.getInstance();
    console.log("modalindex:", this.modalindex);
    if (this.modalindex == 0) {
      console.log("转移金额:", this.operator_count);
      console.log("转移对象:", this.selectedObject);
      console.log("原来对象:", this.recipy_ori_name,  this.singleton_username.zh2en(this.recipy_ori_name));
      this.recipyDetailsService.postTransfer(
        this.singleton_username.add2enname('0x' + this.useraddress), 
        this.singleton_username.zh2en(this.recipy_ori_name), 
        this.selectedObject, 
        this.operator_count).subscribe(str => {
          if (str.state === true) {
            this.ngOnInit();
          }
      });
      this.operator_count = 0;
      this.selectedObject = undefined;
      this.isVisible = false;
    } else if (this.modalindex == 1) {
      console.log("融资金额:", this.operator_count);
      console.log("操作对象:", this.singleton_username.zh2en(this.recipy_ori_name),  this.singleton_username.zh2en(this.recipy_ori_name));
      this.recipyDetailsService.postBankHelp(this.singleton_username.add2enname('0x' + this.useraddress), this.singleton_username.zh2en(this.recipy_ori_name), this.operator_count).subscribe(str => {
        if (str.state === true) {
          this.ngOnInit();
        }
      });
      this.operator_count = 0;
      this.isVisible = false;
    } else if (this.modalindex == 2) {
      console.log("支付金额:", this.operator_count);
      console.log("操作对象:", this.singleton_username.add2enname('0x' + this.useraddress),  this.singleton_username.zh2en(this.recipy_ori_name));
      if (this.singleton_username.zh2en(this.recipy_ori_name) === 'bank') {
        this.recipyDetailsService.postPayBank(this.singleton_username.add2enname('0x' + this.useraddress), this.operator_count).subscribe(str => {
          if (str.state === true) {
            this.ngOnInit();
          }
        });
      } else {
        this.recipyDetailsService.postPayHelp(this.singleton_username.add2enname('0x' + this.useraddress), this.singleton_username.zh2en(this.recipy_ori_name), this.operator_count).subscribe(str => {
          if (str.state === true) {
            this.ngOnInit();
          }
        });
      }
      this.operator_count = 0;
      this.isVisible = false;
    } else if (this.modalindex == 3) {
      console.log("转移金额:", this.operator_count);
      console.log("转移对象:", this.selectedObject);
      console.log("原来对象:", this.recipy_ori_name,  this.singleton_username.zh2en(this.recipy_ori_name));
      this.recipyDetailsService.postTransfer(
        this.singleton_username.zh2en(this.recipy_ori_name), 
        this.singleton_username.add2enname('0x' + this.useraddress), 
        this.selectedObject, 
        this.operator_count).subscribe(str => {
          if (str.state === true) {
            this.ngOnInit();
          }
      });
      this.operator_count = 0;
      this.selectedObject = undefined;
      this.isVisible = false;
    }
  }

  ngOnInit(): void {
    this.debtBillItems = [];
    this.debtHoldingBillItems = [];
    this.singleton_username = Singleton.getInstance();
    this.username = this.singleton_username.getUserName();
    if (this.username == undefined) {
      alert('请右上角退出登录后重新登录');
    }
    this.listOfOption = this.recipyDetailsService.getOptionalObject(this.username);
    this.recipyDetailsService.name2Add(this.username).subscribe(str => {
      if (str.state === true) {
        let len = str.response.length;
        this.useraddress = str.response.substring(2, len);
        for (let i = 0; i <= 65 - len; ++i) {
          this.useraddress = '0' + this.useraddress;
        }
        console.log(this.useraddress);
      }
    });
    this.recipyDetailsService.getDebtWholeInfo(this.username).subscribe(str => {
      if (str.state === true) {
        this.toSplit = str.response;
        let toSplitJson: longDataEntity = JSON.parse(this.toSplit);
        console.log('toSplitJson:', toSplitJson);
        for(let i = 0; i < toSplitJson.logs.length; i++) {
          let from_address = toSplitJson.logs[i].data.substr(2, 64);
          let to_address = toSplitJson.logs[i].data.substr(66, 64);
          let money = Number('0x' + toSplitJson.logs[i].data.substr(130, 64));
          let time = Number('0x' + toSplitJson.logs[i].data.substr(194, 64));
          console.log(from_address, from_address.length, to_address, to_address.length, money, time);
          if (from_address === this.useraddress) {
            this.debtBillItems.push({
              name: this.singleton_username.add2name('0x' + to_address),
              time: String(time),
              moneyCount: money
            });
            this.debtBillItems = [...this.debtBillItems];
          }
          if (to_address === this.useraddress) {
            this.debtHoldingBillItems.push({
              name: this.singleton_username.add2name('0x' + from_address),
              time: String(time),
              moneyCount: money
            });
            this.debtHoldingBillItems = [...this.debtHoldingBillItems];
          }
          this.def.detectChanges();
        }
      }
    });
    // this.debtBillItems = this.recipyDetailsService.getDebtBillItemsWhole(this.username);
    // this.debtHoldingBillItems = this.recipyDetailsService.getDebtHoldingBillItemsWhole(this.username);
  }
}
